package lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * .
 *
 * @author <a href="mailto:sunhao.java@gmail.com">sunhao(sunhao.java@gmail.com)</a>
 * @date 2018/7/2 下午9:21
 */
public class LockTest {
    public String name;

    public LockTest(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        Lock lock = new ReentrantLock(true);

        Thread t1 = new TestThread(lock, new LockTest("test1"));
        Thread t2 = new TestThread(lock, new LockTest("test2"));

        t1.start();
        System.out.println("=====");
        t2.start();
    }
}

class TestThread extends Thread {
    private Lock lock;
    private LockTest lockTest;

    public TestThread(Lock lock, LockTest lockTest) {
        this.lock = lock;
        this.lockTest = lockTest;
    }

    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            try {
                lock.lock();
                System.out.println(lockTest.name + " is locking!");

//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            } finally {
                lock.unlock();
            }
        }
    }
}